package com.maple.utils.widget.timer

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.util.Timer
import kotlin.concurrent.fixedRateTimer
class MyTimer(private val task: MyTimerTask,private val period: Long = 1000): DefaultLifecycleObserver {

    private var timer: Timer? = null

    private var isRunning: Boolean = false

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        // 执行定时任务，每隔1秒钟执行一次
        timer = fixedRateTimer("timer", false, 1000, period) {
            if (isRunning) {
                task.onTask()
            }
        }
    }



    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        isRunning = true
    }



    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        isRunning = false
    }



    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        isRunning = false
        timer?.cancel()
        timer = null
    }




}